<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm1" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="标题" prop="title">
          <el-input
            v-model="queryParams.title"
            placeholder="请输入标题"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="知识编号" prop="knowleNum">
          <el-input
            v-model="queryParams.knowleNum"
            placeholder="请输入知识编号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="内容" prop="contents">
          <el-input
            v-model="queryParams.contents"
            placeholder="请输入内容"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="分类" prop="claifica">
          <treeselect v-model="queryParams.claifica"
                      :options="claificaOptions"
                      :normalizer="normalizer"
                      placeholder="选择类型"
                      style="width: 220px;" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
      <el-table
        :data="knowleBaseList"
        stripe
        border
        style="width: 100%">
        <el-table-column
          prop="index"
          label="序号"
          type = "index">
        </el-table-column>
        <el-table-column
          prop="knowleNum"
          label="知识编号">
        </el-table-column>
        <el-table-column
          prop="claificaName"
          label="分类名称"
          align="center">
        </el-table-column>
        <el-table-column
          prop="title"
          label="标题"
          align="center">
        </el-table-column>
        <el-table-column
          prop="readNum"
          label="阅读量"
          sortable
          align="center">
        </el-table-column>
        <el-table-column
          prop="delFlag"
          label="状态"
          align="center">
          <template slot-scope="scope">
            <span>{{scope.row.delFlag === "1" ?"未发布":'发布'}}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="userName"
          label="添加人"
          align="center">
        </el-table-column>
        <el-table-column
          prop="version"
          :formatter="verFormat"
          label="版本号"
          align="center">
        </el-table-column>
        <el-table-column
          prop="updateTime"
          label="最新发布日期"
          align="center">
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="viewContent(scope.row)"
              v-hasPermi="['view:all:list']">
              查看内容
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['know:edit']">
              修改
            </el-button>
            <el-dropdown size="mini" trigger="click"  @command="(command) => handleCommand(command, scope.row)" v-hasPermi="['know:more']">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-d-arrow-right">
                更多
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="del" icon="el-icon-delete">删除</el-dropdown-item>
                <el-dropdown-item command="viewHistorVer" icon="el-icon-view">查看历史版本</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
      <!--修改-->
      <el-dialog
        :title="title"
        :visible.sync="open"
        width="50%"
        :close-on-click-modal="false"
        :before-close="handleClose"
        append-to-body>
        <el-form :inline="true" ref="form" :model="form" :rules="rules">
          <el-form-item label="标题"  prop="title">
            <el-input v-model="form.title" :disabled="disRecord" style="width:500px" placeholder="标题"></el-input>
          </el-form-item>
          <el-form-item label="分类"  prop="claifica">
            <treeselect v-model="form.claifica"
                        :options="claificaOptions"
                        :normalizer="normalizer"
                        placeholder="选择类型"
                        style="width: 220px;" />
          </el-form-item>
          <el-form-item label="内容" prop="contents">
            <editor v-model="form.contents" :min-height="540"/>
          </el-form-item>
          <el-form-item  v-if="disRecord" label="更新日志" prop="updateRecords">
            <el-input
              type="textarea"
              style="min-width:540px;"
              :autosize="{ minRows: 5}"
              placeholder="请输入更新日志"
              v-model="form.updateRecords">
            </el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="stagForm">暂 存</el-button>
        <el-button type="primary" @click="submitForm">发 布</el-button>
      </span>
      </el-dialog>
    </div>
</template>

<script>
import { allKnowBase, getKnowBase, editKnowLeBase, addKnowLeBase, editDelKnowLeBase } from '@/api/knowledge/knowBase'
  import {getClaificaTree} from "@/api/knowledge/claifica";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { addStag, getExist, updateStag } from '@/api/knowledge/staging'
import { updateContent } from '@/api/knowledge/content'
import { delUser } from '@/api/system/user'

  export default {
    name: "allKnowle",
    components: {
      Treeselect
    },
    data() {
      const validConten=(rule,value,callback)=>{
        value=this.getText(value);
        value.trim().length==0?callback(new Error("知识内容不能为空")):callback();
      }
      return {
        rules: {
          title: [
            { required: true, message: '请输入标题', trigger: 'blur' }
          ],
          claifica: [
            { required: true, message: '请选择知识类型', trigger: 'blur' }
          ],
          contents: [
            { required: true, message: '知识内容不能为空', trigger: 'blur' },
            { validator: validConten, trigger: 'blur'}
          ],
          updateRecords: [
            { required: true, message: '更新日志不能为空', trigger: 'blur' }
          ]
        },
        queryParams:{
          pageNum: 1,
          pageSize: 10,
          orderByColumn: '',
          isAsc: 'desc',
          title: null,
          content: null,
          claifica:null,
          knowleNum:null,
          dept:null
        },
        open: false,
        disRecord:true,
        title:'',
        form:{},
        knowleBaseList:[],
        versionList: [],
        // 显示搜索条件
        showSearch: true,
        claificaOptions:[],
        // 知识库分类表格数据
        claificaList: [],
        // 总条数
        total: 0,
      }
    },
    methods:{
      historVers(row){
        const params = { id:row.id };
        this.$tab.openPage("历史版本", "/knowledge/knowlebase/historVers",params);
        /*this.openver=true;
        getVersion(row.id).then(response => {
          this.versionList = response.data;
        })*/
      },
      delKnow(row){
        this.$modal.confirm('是否确认删除？').then(function() {
          return editDelKnowLeBase(row.id);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      handleCommand(command,row){
        switch (command) {
          case "viewHistorVer":
            this.historVers(row);
            break;
          case "del":
            this.delKnow(row);
            break;
          default:
            break;
        }
      },
      getText(str) {
        return str
          .replace(/<[^<p>]+>/g, '')  // 将所有<p>标签 replace ''
          .replace(/<[</p>$]+>/g, '')  // 将所有</p>标签 replace ''
          .replace(/&nbsp;/gi, '')  // 将所有 空格 replace ''
          .replace(/<[^<br/>]+>/g, '') // 将所有 换行符 replace ''
      },
      stagForm(){
        this.rules.updateRecords=[]
        this.$refs["form"].validate(async valid => {
          if(valid){
            if(this.form.sid!=null){
              updateStag(this.form).then(res=>{
                this.$modal.msgSuccess("操作成功");
                this.getList()
              })
            }else{
              //判断是否存在
              let exist = await getExist(this.form.id).then(resopnse=>{
                return resopnse.data;
              })
              if(exist){
                this.$modal.msgSuccess("已有暂存，请在最新版本修改");
                return
              }

              if(this.form.delFlag==="1"){
                this.form.id=this.form.contentId
                await updateContent(this.form).then(response=>{
                  this.$modal.msgSuccess("操作成功");
                })
              }else{
                await addStag(this.form).then(response=>{
                  this.$modal.msgSuccess("操作成功");
                })
              }
              await this.getList()
            }
            this.getList();
            this.open=false;
          }
        })
      },
      submitForm(){
        this.rules.updateRecords=[
          { required: true, message: '更新日志不能为空', trigger: 'blur' }
        ]
        this.$refs["form"].validate(valid => {
          if(valid){
            if(this.form.id!=null){
              this.form.delFlag="2"
              editKnowLeBase(this.form).then(response=>{
                this.$modal.msgSuccess("操作成功");
                this.getList();
                this.getList();
              });
            }else{
              addKnowLeBase(this.form).then(response=>{
                this.$modal.msgSuccess("新增成功");
                this.getList();
                this.getList();
              });
            }
            this.open=false;
          }
        });

      },
      cancel(){
        this.open=false;
        // this.disRecord=false;
        this.reset();
      },
      handleClose(done){
        this.disRecord=true;
        done();
      },
      handleUpdate(row){
        this.reset();
        if(row.delFlag==='1'){
          this.disRecord=false;
        }
        getKnowBase(row.id).then(response=>{
          this.form = response.data;
          this.form.contentId=row.contentId;
          this.form.delFlag=row.delFlag;
          this.open = true;
          this.title = "修改知识库内容";
        })

      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm1");
        this.handleQuery();
      },
      getList(){
        allKnowBase(this.queryParams).then(resoponse=>{
          console.log(resoponse.rows)
          this.knowleBaseList=resoponse.rows;
          this.total=resoponse.total;
        });
      },
      reset(){
        this.form={
          id:null,
          /*标题*/
          title:null,
          /*内容*/
          content:null,
          /*分类*/
          claifica:null,
          /*更新日志*/
          updateRecords:null
        };
        this.resetForm("form");
      },
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.id,
          label: node.label,
          children: node.children
        };
      },
      getTree(){
        getClaificaTree().then(response=>{
          this.claificaOptions=response.data;
        })
      },
      viewContent(row){
        const params = { id:row.id };
        this.$tab.openPage("历史版本", "/knowledge/knowlebase/historVers",params);
      },
      verFormat(row, column){
        return row.version===0?"初始版本":row.version
      },
    },
    created() {
      const column=this.$route.query.column?this.$route.query.column:"kb.knowle_num";
      console.log(column);
      this.queryParams.orderByColumn=column;
      this.getList();
      this.getTree();
    },
    watch:{
      "queryParams":{
        handler(value){
          const column=this.$route.query.column?this.$route.query.column:"kb.knowle_num";
          this.queryParams.orderByColumn=column;
          this.getList();
        }
      }
    },
  }
</script>

<style scoped>

</style>
